// components/img-uploader-tool/s-uploader.js
const mybehavior = require("../../behaviors/requests")
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [mybehavior],
  properties: {
    fs_upload_url: {
      type: String,
      value: "",
    },

    label_val: {
      type: String,
      value: "",
    },
    uploader: {
      type: Array,
      value: [],
    },
    choose_img_btn_disabled: {
      type: Boolean,
      value: false,
    },
    img_required: {
      type: Boolean,
      value: true,
    },
    deletable_flag: {
      type: Boolean,
      value: true,
    },
    picker_size: {
      type: String,
      value: ''
    },
    img_count: {
      type: Number,
      value: 3
    },

  },

  /**
   * 组件的初始数据
   */
  data: {
  },

  /**
   * 组件的方法列表
   */
  attached() {
    // const uploader = this.data.uploader;
    // if (uploader.length != 0) {
    //   let arr = []
    //   for (let i in uploader) {
    //     let obj = {
    //       url: this.data.fs_upload_url +'/fs_download?file_id='+  uploader[i],
    //       isImage: true,
    //       file_id: uploader[i]
    //     }
    //     arr.push(obj)
    //   }
    //   this.setData({
    //     uploader:arr
    //   })

    // }

  },
  methods: {
    handle_delete(e) {
      const index = e.detail.index;
      const file = this.data.uploader[index];
      const file_id = file.url.split("=")[1];
      const uploader = this.data.uploader;
      const self = this;

      let url1 = self.data.fs_upload_url + '/fs_delete'
      let data = {
        file_id
      }
      this.post(url1, data).then(res => {
        if (res.code == 20000) {
          wx.showToast({
            title: res.msg,
            icon: 'success'
          })

          uploader.splice(index, 1);
          self.setData({
            choose_img_btn_disabled: false,
          })
          self.setData({
            uploader
          });
          self.triggerEvent("setValue", self.data.uploader);


        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    },
    // 照片选取
    try_upload(e) {
      console.log(e);

      const self = this;
      // 关闭照片选取
      self.setData({
        choose_img_btn_disabled: true
      });
      // 确定还有张图片可以选择
      const count = self.data.img_count - self.data.uploader.length;
      wx.chooseMedia({
        count: count,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          const myUploadFiles = res.tempFiles.map(tempFile => {
            const tempFilePath = tempFile.tempFilePath;
            return self.myUploadFile(tempFilePath);
          });
          wx.showLoading({
            title: '开始上传。。。',
          })
          Promise.all(myUploadFiles).then(file_ids => {
            wx.hideLoading();
            // 处理UI
            console.log(file_ids);
            const uploader = self.data.uploader;

            const new_uploader = uploader.concat(file_ids.map(file_id => {
              return {
                url: self.data.fs_upload_url + '/fs_download?file_id=' + file_id,
                isImage: true,
                file_id: file_id

              };
            }));
            self.setData({
              uploader: new_uploader
            })
            console.log("xxx",self.data.uploader);
            self.triggerEvent("setValue", self.data.uploader);
            if (self.data.uploader.length < self.data.img_count) {
              self.setData({
                choose_img_btn_disabled: false
              });
            }
            wx.showToast({
              title: '上传成功！',
            });

          }).catch(msg => {
            wx.hideLoading();
            if (self.data.uploader.length < self.data.img_count) {
              self.setData({
                choose_img_btn_disabled: false
              })
            }
            wx.showToast({
              title: msg,
              icon: "error"
            })
            console.log(msg);
          });
        },
        fail() {
          if (self.data.uploader.length < self.data.img_count) {
            self.setData({
              choose_img_btn_disabled: false
            })
          }
        }
      })
    },
    myUploadFile(file) {
      let self = this
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: self.data.fs_upload_url + '/fs_upload',
          filePath: file,
          name: 'file',
          formData: {},
          success(res) {
            const result = JSON.parse(res.data);
            console.log(result);
            wx.hideLoading();
            if (result.code == 20000) {
              resolve(result.data.file_id);
            } else {
              reject(result.msg);
            }

          },
          fail() {
            reject("未知错误446");
          }
        })
      });
    },

  }
})
